package com.wan.interceptor;

import com.wan.pojo.Menu;
import com.wan.utils.MenuUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//登录拦截器

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        Object admin = request.getSession().getAttribute("admin");
        if(admin==null){
            //表示未登录或登录失效

            //判断是否为ajax请求（X-Requested-With: XMLHttpRequest）
            String header = request.getHeader("X-Requested-With");
            if("XMLHttpRequest".equals(header)){
                //表示是ajax请求
                Map<String, String> map = new HashMap<String, String>();
                map.put("type","error");
                map.put("msg","登录会话超时或未登录，请重新登录！");
                response.getWriter().write(JSONObject.fromObject(map).toString());
                return false;
            }
            //表示是普通跳转连接，直接重定向
            response.sendRedirect(request.getContextPath()+"/system/login");
            return false;
        }

        //获取菜单id（从index.jsp页面传来的）
        String mid = request.getParameter("_mid");
        if(!StringUtils.isEmpty(mid)){
            List<Menu> menuList = (List<Menu>) request.getSession().getAttribute("userMenus");
            List<Menu> allThirdMenu = MenuUtil.getAllThirdMenu(menuList, Long.valueOf(mid));
            request.setAttribute("thirdMenuList", allThirdMenu);
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
